#include "sc.h"

NeighbourhoodToPixelOp()
interpolate(in stream unsigned char i[-1..0][-1..0],
	 out stream unsigned char *o)
{
  *o = i[-1][0]*0.24 + i[-1][-1]*0.24 + i[0][-1]*0.24 + i[0][0]*0.24;
}

NeighbourhoodToPixelOp()
sobelx(in stream unsigned char i[-1..1][-1..1],
       out stream unsigned char *o)
{
  int x, y, temp;
  
  temp = 0;
  for (y=-1; y < 2; y++)
    for (x=-1; x < 2; x=x+2)
      temp = temp + x*i[y][x];

  if (temp < 0) *o = temp*-0.49;
  else          *o = temp*0.49;
}

NeighbourhoodToPixelOp()
sobely(in stream unsigned char i[-1..1][-1..1],
       out stream unsigned char *o)
{
  int x, y, temp;
  
  temp = 0;
  for (x=-1; x < 2; x++)
    for (y=-1; y < 2; y=y+2)
      temp = temp + y*i[y][x];

  if (temp < 0) *o = temp*-0.49;
  else          *o = temp*0.49;
}

PixelToPixelOp()
combine(in stream unsigned char *i1,
	in stream unsigned char *i2,
	out stream unsigned char *o)
{
 *o = *i1*0.49 + *i2*0.49;
}

PixelToPixelOp()
binarize(in stream unsigned char *i,
	 out stream unsigned char *o,
	 in int *threshold=scint(128),
	 in int *value=scint(255))
{
  if (*i > *threshold) *o = *value;
  else                 *o = 0;
}

PixelToPixelOp()
add(in stream unsigned char *i1, in stream unsigned char *i2,
	out stream unsigned char *o)
{
  *o = *i1 + *i2;
}

StackOp(in stream unsigned char **init, in int *threshold=scint(0))
propagation(in stream unsigned char i[-1..1][-1..1],
	        out stream unsigned char *o)
{  
  int x, y;

  if (*o != 255)
  {
    *o = 255;

    for (y=-1; y < 2; y++)
      for (x=-1; x < 2; x++)
	if (y != 0 || x != 0)
	  if (i[y][x] && (i[y][x] != 255))
	    addtostack(y, x);
  }
}

PixelToPixelOp()
split(in stream unsigned char *i, out stream unsigned char *o1, out stream unsigned char *o2)
{
  *o1 = *i;
  *o2 = *i;
}

#ifdef PSOS  
#define MAINPROTO(x) MAIN(void)
#define argc _argc
#define argv _argv
#define LOGINIT() liblog_init()
#else
#define MAINPROTO(x) MAIN(int argc, char **argv)
#define LOGINIT()
#endif

int MAINPROTO(void)
{
  int i;
  STREAM a, b, c;

  /* Assemble command line */
  int _argc=8;
  char *_argv[8] = {"sctest", "-n", "TriMedia", "-m", "/flash/machines", "-a", "/flash/availability.txt", "-c"};

  LOGINIT();

  scInit(argc, argv);

  /* while(1) */
  {
    capture(&a);
    interpolate(&a, &a);
/*
    split(&a, &a, &b);
    sobelx(&a, &a);
    sobely(&b, &b);
    combine(&a, &b, &a);
    split(&a, &a, &b);
*/
    binarize(&a, &a, scint(64), scint(64));
    binarize(&a, &a, scint(128), scint(128));
/*
    binarize(&b, &b, scint(32), scint(32));
    add(&a, &b, &a);
    _finalize(&b);

    StackOp(&a, scint(64), propagation, &a, &a);
*/
    display(&a);
    _block(&a);
  }

  return scExit();
}
